<script setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { listMajorsByCollege } from "@/api/major.js";
import { listClassesByMajor } from "@/api/classes.js";
import { listColleges } from "@/api/college.js";
import { listBorrowsForStudentsService } from "@/api/borrowing.js";
import moment from "moment";

const colleges = ref([]);
const majors = ref([]);
const classes = ref([]);
const borrowsData = ref([]);
const pageNum = ref(1);
const pageSize = ref(10000);
const total = ref(0);
const selectedYear = ref(null);
const selectedSemester = ref(null);
import * as XLSX from "xlsx";

const searchBorrow = ref({
  collegeId: "",
  majorId: "",
  classId: "",
  semesterStartDate: "",
  semesterEndDate: "",
});

const statistics = ref({
  totalBorrows: 0,
  totalReturns: 0,
  lostBooks: 0,
  overdueReturns: 0,
  onTimeReturns: 0,
  notReturned: 0,
});

const reset = async () => {
  searchBorrow.value = {
    collegeId: "",
    majorId: "",
    classId: "",
    semesterStartDate: "",
    semesterEndDate: "",
  };
  selectedYear.value = null;
  selectedSemester.value = null;
  await listBorrows();
};

const handleCollegeChange = async (collegeId) => {
  searchBorrow.value.majorId = "";
  searchBorrow.value.classId = "";
  majors.value = (await listMajorsByCollege(collegeId)).data;
};

const handleMajorChange = async (majorId) => {
  searchBorrow.value.classId = "";
  classes.value = (await listClassesByMajor(majorId)).data;
};

const handleYearChange = (year) => {
  selectedYear.value = year;
  selectedSemester.value = null;
};

const handleSemesterChange = (semester) => {
  const year = selectedYear.value.getFullYear(); // 从 Date 对象中提取年份
  console.log("Selected Year:", year);
  if (!year || isNaN(year)) {
    console.error("Invalid year:", year);
    return;
  }

  if (semester === "first") {
    searchBorrow.value.semesterStartDate = moment(`${year}-09-01`).format(
      "YYYY-MM-DD",
    );
    searchBorrow.value.semesterEndDate = moment(`${year + 1}-01-19`).format(
      "YYYY-MM-DD",
    );
  } else if (semester === "second") {
    searchBorrow.value.semesterStartDate = moment(`${year}-02-19`).format(
      "YYYY-MM-DD",
    );
    searchBorrow.value.semesterEndDate = moment(`${year}-07-01`).format(
      "YYYY-MM-DD",
    );
  }
};

const formatDate = (row, column, cellValue) => {
  if (!cellValue) return "未归还";
  return moment(cellValue).format("YYYY-MM-DD");
};

const updateStatistics = () => {
  statistics.value.totalBorrows = borrowsData.value.length;
  statistics.value.totalReturns = borrowsData.value.filter(
    (borrow) => borrow.returnDate,
  ).length;
  statistics.value.lostBooks = borrowsData.value.filter(
    (borrow) => borrow.status === "丢失",
  ).length;
  statistics.value.overdueReturns = borrowsData.value.filter(
    (borrow) =>
      borrow.returnDate && moment(borrow.returnDate).isAfter(borrow.dueDate),
  ).length;
  statistics.value.onTimeReturns = borrowsData.value.filter(
    (borrow) =>
      borrow.returnDate && moment(borrow.returnDate).isBefore(borrow.dueDate),
  ).length;
  statistics.value.notReturned = borrowsData.value.filter(
    (borrow) => !borrow.returnDate,
  ).length;
};

const listBorrows = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchBorrow.value,
  };
  console.log("params", params);
  let result = await listBorrowsForStudentsService(params);
  total.value = result.data.total;
  borrowsData.value = result.data.records;
  console.log("data:", result.data.records);
  updateStatistics();
};

const fetchColleges = async () => {
  let result = await listColleges();
  console.log("result::", result);
  colleges.value = result.data;
};

const statusCellStyle = ({ row, column }) => {
  if (column.property === "returnDate") {
    if (row.returnDate && moment(row.returnDate).isAfter(row.dueDate)) {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    } else if (row.returnDate && moment(row.returnDate).isBefore(row.dueDate)) {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    } else if (!row.returnDate && moment().isAfter(row.dueDate)) {
      return { backgroundColor: "rgba(235, 181, 99, 0.3)" }; // 黄色
    }
  } else if (column.property === "paymentStatus") {
    if (row.paymentStatus === "未缴款") {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    } else if (row.paymentStatus === "已缴款") {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    }
  } else if (column.property === "renewalStatus") {
    if (row.renewalStatus === "可续借") {
      return { backgroundColor: "rgba(133, 206, 97, 0.3)" }; // 绿色
    } else if (row.renewalStatus === "不可续借") {
      return { backgroundColor: "rgba(247, 137, 137, 0.3)" }; // 红色
    }
  } else if (column.property === "status") {
    switch (row.status) {
      case "未借阅":
        // 设置为50%透明度
        return { backgroundColor: "rgba(133, 206, 97, 0.3)" };
      case "已借阅":
        // 设置为50%透明度
        return { backgroundColor: "rgba(247, 137, 137, 0.3)" };
      default:
        // 设置为50%透明度
        return { backgroundColor: "rgba(235, 181, 99, 0.3)" };
    }
  }
  return {};
};

const fineFormatter = (row, column, cellValue) => {
  return cellValue === null ? "无需缴款" : cellValue;
};

const filterHandler = (value, row, column) => {
  const property = column.property;
  return row[property] === value;
};
const exportToExcel = () => {
  const data = borrowsData.value.map(borrow => ({
    借阅ID: borrow.borrowingId,
    学生姓名: borrow.studentName,
    学院: borrow.collegeName,
    专业: borrow.majorName,
    班级: borrow.className,
    读者类别: borrow.categoryName,
    图书ID: borrow.bookId,
    ISBN: borrow.isbn,
    书名: borrow.bookName,
    图书类别: borrow.description,
    语言: borrow.language,
    图书状态: borrow.status,
    学号: borrow.studentId,
    用户ID: borrow.userId,
    关联用户名: borrow.username,
    借阅日期: formatDate(null, null, borrow.borrowDate),
    到期日期: formatDate(null, null, borrow.dueDate),
    归还日期: formatDate(null, null, borrow.returnDate),
    续借状态: borrow.renewalStatus,
    缴款金额: fineFormatter(null, null, borrow.totalAmount),
    缴款状态: fineFormatter(null, null, borrow.paymentStatus),
  }));

  const worksheet = XLSX.utils.json_to_sheet(data);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "借阅记录");

  XLSX.writeFile(workbook, "借阅记录.xlsx");
};

listBorrows();
fetchColleges();
</script>

<template>
  <div class="search-container">
    <el-select
      v-model="searchBorrow.collegeId"
      placeholder="请选择学院"
      @change="handleCollegeChange"
    >
      <el-option
        v-for="college in colleges"
        :key="college.collegeId"
        :label="college.collegeName"
        :value="college.collegeId"
      />
    </el-select>
    <el-select
      v-model="searchBorrow.majorId"
      placeholder="请选择专业"
      @change="handleMajorChange"
      :disabled="!searchBorrow.collegeId"
    >
      <el-option
        v-for="major in majors"
        :key="major.majorId"
        :label="major.majorName"
        :value="major.majorId"
      />
    </el-select>
    <el-select
      v-model="searchBorrow.classId"
      placeholder="请选择班级"
      :disabled="!searchBorrow.majorId"
    >
      <el-option
        v-for="cls in classes"
        :key="cls.classId"
        :label="cls.className"
        :value="cls.classId"
      />
    </el-select>
    <el-date-picker
      v-model="selectedYear"
      type="year"
      placeholder="请选择年份"
      @change="handleYearChange"
      style="width: 100%"
    />
    <el-select
      v-model="selectedSemester"
      placeholder="请选择学期"
      :disabled="!selectedYear"
      @change="handleSemesterChange"
    >
      <el-option label="第一学期" value="first" />
      <el-option label="第二学期" value="second" />
    </el-select>
  </div>

  <div class="statistics-container">
    <div class="statistics-item">
      <span class="statistics-label">总借阅数:</span>
      <span class="statistics-value">{{ statistics.totalBorrows }}</span>
    </div>
    <div class="statistics-item">
      <span class="statistics-label">总归还数:</span>
      <span class="statistics-value">{{ statistics.totalReturns }}</span>
    </div>
    <div class="statistics-item">
      <span class="statistics-label">丢失书本数:</span>
      <span class="statistics-value">{{ statistics.lostBooks }}</span>
    </div>
    <div class="statistics-item">
      <span class="statistics-label">超期归还数:</span>
      <span class="statistics-value">{{ statistics.overdueReturns }}</span>
    </div>
    <div class="statistics-item">
      <span class="statistics-label">按时归还数:</span>
      <span class="statistics-value">{{ statistics.onTimeReturns }}</span>
    </div>
    <div class="statistics-item">
      <span class="statistics-label">未归还数:</span>
      <span class="statistics-value">{{ statistics.notReturned }}</span>
    </div>
    <div class="button-group">
      <el-button @click="exportToExcel" type="success">导出Excel</el-button>
      <el-button @click="listBorrows()" type="primary">生成报表</el-button>
      <el-button @click="reset" type="warning" icon="RefreshRight"
        >重置</el-button
      >
    </div>
  </div>
  <el-table
    :data="borrowsData"
    :cell-style="statusCellStyle"
    :header-cell-style="{ background: '#2a598a', color: '#ffffff' }"
    border
    stripe
    :max-height="500"
    style="width: 100%"
    highlight-current-row
  >
    <el-table-column
      fixed
      sortable
      prop="borrowingId"
      label="借阅ID"
      width="130"
    />
    <el-table-column
      fixed
      sortable
      prop="studentName"
      label="学生姓名"
      width="130"
    />
    <el-table-column sortable prop="collegeName" label="学院" width="130" />
    <el-table-column sortable prop="majorName" label="专业" width="130" />
    <el-table-column sortable prop="className" label="班级" width="130" />
    <el-table-column
      sortable
      prop="categoryName"
      label="读者类别"
      width="130"
      :filters="[
        { text: '非教研人员', value: '非教研人员' },
        { text: '博士研究生', value: '博士研究生' },
        { text: '硕士研究生', value: '硕士研究生' },
        { text: '本科生', value: '本科生' },
        { text: '专科生', value: '专科生' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column sortable prop="bookId" label="图书ID" width="130" />
    <el-table-column sortable prop="isbn" label="ISBN" width="130" />
    <el-table-column sortable prop="bookName" label="书名" width="130" />
    <el-table-column sortable prop="description" label="图书类别" width="130" />
    <el-table-column
      sortable
      prop="language"
      label="语言"
      width="130"
      :filters="[
        { text: '中文', value: '中文' },
        { text: '外文', value: '外文' },
        { text: '新书', value: '新书' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column
      sortable
      prop="status"
      label="图书状态"
      width="130"
      :filters="[
        { text: '已借阅', value: '已借阅' },
        { text: '未借阅', value: '未借阅' },
        { text: '丢失', value: '丢失' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column sortable prop="studentId" label="学号" width="130" />
    <el-table-column sortable prop="userId" label="用户ID" width="130" />
    <el-table-column sortable prop="username" label="关联用户名" width="130" />
    <el-table-column
      sortable
      prop="borrowDate"
      label="借阅日期"
      :formatter="formatDate"
      width="130"
    />
    <el-table-column
      sortable
      prop="dueDate"
      label="到期日期"
      :formatter="formatDate"
      width="130"
    />
    <el-table-column
      sortable
      prop="returnDate"
      label="归还日期"
      :formatter="formatDate"
      width="130"
    />
    <el-table-column
      sortable
      prop="renewalStatus"
      label="续借状态"
      width="130"
      :filters="[
        { text: '可续借', value: '可续借' },
        { text: '不可续借', value: '不可续借' },
      ]"
      :filter-method="filterHandler"
    />
    <el-table-column
      sortable
      prop="totalAmount"
      label="缴款金额"
      :formatter="fineFormatter"
      width="130"
    />
    <el-table-column
      sortable
      prop="paymentStatus"
      label="缴款状态"
      :formatter="fineFormatter"
      width="130"
      :filters="[
        { text: '已缴款', value: '已缴款' },
        { text: '未缴款', value: '未缴款' },
      ]"
      :filter-method="filterHandler"
    />/>
  </el-table>
</template>

<style scoped>
.statistics-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.statistics-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.statistics-label {
  font-weight: bold;
  margin-bottom: 10px;
}

.statistics-value {
  font-size: 1.5em;
  color: #2a598a;
  margin-left: 10px;
  margin-bottom: 10px;
}

.search-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>
